﻿using Microsoft.EntityFrameworkCore;
using WebService.EF;
using WebService.Models;
using YaseiAkira.AJ.Util;

namespace WebService.Authorize
{
    public class SystemUserChecker : IChecker
    {
        private long _id;
        private int _pid;
        public SystemUserChecker(long id, int pid)
        {
            _id = id;
            _pid = pid;
        }
        public void ProcessUser(HttpContext httpContext, Action<CommonAuthUser> success, Action<string> failed, Action<string> noAccess)
        {
            var user = Util.TryGetOrCreateMemoryCached(_id.ToString(), "auth", () =>
            {
                using var db = DbServiceExt.GetDb();
                return db.SystemUsers.Where(p => p.Id == _id).AsNoTracking().FirstOrDefault();
            });

            if (user == null)
            {
                failed?.Invoke("账户信息不存在");
                return;
            }

            if (!user.Enable)
            {
                failed?.Invoke("账户已禁用");
                return;
            }


            success.Invoke(new CommonAuthUser
            {
                Id = user.Id,
                Type = IdentityType.System,
                Name = user.NickName,
                Role = user.RoleId.ToString(),
                PId = _pid,
                //StationId = user.StationId
            });

        }
    }
}
